clear;
clc;
filepath = '.\';
outputfolder=strcat(filepath,'\model_output\');
close all;

%% Floating lien: W-K plot
data = readtable('BPDL 25000 distribution.csv');
data=data(data.bin<=65000,:);
ell = 0.24;
R = 1.04;
phi = 2300;
gamma_data= sum(data.freq(data.bin>25000&data.bin<=35000))/sum(data.cf(data.bin>25000&data.bin<=35000));
gamma_vec = [1 1 gamma_data gamma_data gamma_data]; % fraction of non-optimizing agents
lambda_vec = [.0 .044 .044 .044 .034];
beta_vec = ell.*[.375 .375 .375 .4 .375];

K_lower_vec = [0:1000:65000];
for k=1:length(gamma_vec)
for i=1:length(K_lower_vec)
W_vec(i,k) = W(lambda_vec(k),K_lower_vec(i),ell,beta_vec(k),gamma_vec(k),phi,R,data);
end
        [M,I]=max(W_vec(:,k));
        K_lower_opt(k) = K_lower_vec(I);
end



%% varying K_bar
y = W_vec(:,[1,2,3,5]);
x = K_lower_vec/10^3;


% Define a cell array of line styles
lineStyles = {'-', '--',':', '-.'};



figure;
hold on
ax = gca;  % Get the current axes
defaultColorOrder = ax.ColorOrder;  % Get the default color order
% Loop through each line and plot with a different line style
for i = 1:size(y, 2)
    plot(x, y(:, i), 'LineStyle', lineStyles{i},'Color',defaultColorOrder(i,:) );
end

% Loop through each line
for i = 1:size(y, 2)
    [yMax, idx] = max(y(:, i));  % Find the maximum value and its index for the i-th line
    xMax = x(idx);  % Get the x-coordinate of the maximum point
    plot(xMax, yMax, 'o', 'MarkerFaceColor',defaultColorOrder(i,:));  % Mark the maximum point with a circle, auto-coloring to match the line color
    % Alternate the vertical alignment based on the index of the line
    verticalAlignment = 'bottom';
    if mod(i,2) == 0  % For even-numbered lines
        verticalAlignment = 'top';
    end
    % Create the label
    text(xMax, yMax, sprintf('%.0f', xMax), ...
        'VerticalAlignment', verticalAlignment, 'HorizontalAlignment', 'right');
end

ylabel('Welfare (per dollar of loan)')
xlabel('Collateral threshold (thousand)')
legend({'No cost','Fixed lien, no manip.','Fixed lien, manip.','Floating lien, manip.'},'Location','southeast','Orientation','vertical')
hold off

fig = gcf;
fig.PaperPositionMode = 'manual'; %'auto'
fig.PaperPosition     = [1.3333    3.3125    5.8333    4.3750];
fig_pos = fig.PaperPosition;
fig.PaperSize = [fig_pos(3) fig_pos(4)];

print(fig,strcat(outputfolder,'optimal_threshold_welfare_fixed_floating'),'-dpdf','-fillpage')


%%
% welfare at the current threshold

fprintf('Fix to floating: %.3f\n', W_vec(26,3)-W_vec(26,5));
fprintf('floating: low to high: %.3f\n', W_vec(26,5)-W_vec(end-2,5));

%% varying phi
phi_vec = [0:100:4000];

for j = 1:size(phi_vec, 2)
    phi = phi_vec(j);
    K_lower_vec = [0:1000:65000];
    for k=1:length(gamma_vec)
        for i=1:length(K_lower_vec)
            W2_vec(i,k) = W(lambda_vec(k),K_lower_vec(i),ell,beta_vec(k),gamma_vec(k),phi,R,data);
        end
        [M,I]=max(W2_vec(:,k));
        K_lower_opt(k,j) = K_lower_vec(I);
    end
    
end

%%
y = K_lower_opt([1,2,3,5],:)'/10^3;
x = phi_vec;


% Define a cell array of line styles
lineStyles = {'-', '--',':', '-.'};


figure;
hold on
ax = gca;  % Get the current axes
defaultColorOrder = ax.ColorOrder;  % Get the default color order
% Loop through each line and plot with a different line style
for i = 1:size(y, 2)
    plot(x, y(:, i), 'LineStyle', lineStyles{i},'Color',defaultColorOrder(i,:) );
end

ylabel('Optimal threshold (thousand)')
xlabel('Fixed cost')
legend({'No cost','Fixed lien, no manip.','Fixed lien, manip.','Floating lien, manip.'},'Location','southeast','Orientation','vertical')
hold off

fig = gcf;
fig.PaperPositionMode = 'manual'; %'auto'
fig.PaperPosition     = [1.3333    3.3125    5.8333    4.3750];
fig_pos = fig.PaperPosition;
fig.PaperSize = [fig_pos(3) fig_pos(4)];

print(fig,strcat(outputfolder,'optimal_threshold'),'-dpdf','-fillpage')
